package com.jvup.common.utils;

import com.jvup.common.support.base.BaseViewModel;

/**
 * 扫描观察者绑定器助手：目前主要扫描 Dal数据访问异常管理注册，ViewModel属性更改触发观察绑定。<br />
 * 目前 Dal数据访问异常管理注册，ViewModel属性更改触发器 代码是有APT自动生成
 */
public class ObserveBinderHelper {

    private static final String PROPERTY_OBSERVE_BINDER = "PropertyObserveBinder";
    private static final String DAL_EXCEPTION_OBSERVE_BINDER = "DalExceptionObserveBinder";

    public static void callObserveBindOfPropertyObserveBinder(BaseViewModel viewModel, Object observe){
        // 简单支持自遍历绑定器能力
        String observeBinderClassName = observe.getClass().getCanonicalName() + PROPERTY_OBSERVE_BINDER;
        com.qire.antsbinder.viewModel.IObserveBinder binder = createObserveBinder(observeBinderClassName);
        if (binder != null) {
            binder.observeBind(viewModel, observe);
        }
    }

    public static void callRegisterOfDalExceptionObserveBinder(Object observe) {
        // 简单支持自遍历绑定器能力
        String observeBinderClassName = observe.getClass().getCanonicalName() + DAL_EXCEPTION_OBSERVE_BINDER;
        com.qire.antsbinder.dal.exception.IObserveBinder binder = createObserveBinder(observeBinderClassName);
        if (binder != null) {
            binder.register(observe);
        }
    }

    public static void callUnregisterOfDalExceptionObserveBinder(Object observe) {
        // 简单支持自遍历绑定器能力
        String observeBinderClassName = observe.getClass().getCanonicalName() + DAL_EXCEPTION_OBSERVE_BINDER;
        com.qire.antsbinder.dal.exception.IObserveBinder binder = createObserveBinder(observeBinderClassName);
        if (binder != null) {
            binder.unregister();
        }
    }

    public static <T> T createObserveBinder(String className){
        try {
            return (T) Class.forName(className).newInstance();
        } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
//            e.printStackTrace();
            Logger.d("未找到观察者绑定器：" + className);
        }
        return null;
    }

}
